iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0

https://ithelp.ithome.com.tw/upload/images/20240921/20139057gMQxEDUwYn.jpg

在應用程式中,如果有大量資料要取得的話,可以透過 Rest API 的 GET records 來取得。不過可以看到 開發文件 上面寫到:

The maximum number of records that can be retrieved with the Get Records API is 500.

沒錯!一次能取得的 record 上限是 500 筆,更新的上限也有限制,如果希望能夠調用一次函式就解決的話,可以使用 kintone-rest-api-client。他的好處是以下:

  • 可以做大量取得資料、更新等行為。
  • 使用 TS 撰寫,有型別支援。
  • 官方維護

安裝 kintone-rest-api-client

老樣子看著文件安裝:

npm install @kintone/rest-api-client

然後可以用 CommonJS 或是 ES modules 引入:

// CommonJS
const { KintoneRestAPIClient } = require('@kintone/rest-api-client')
// ES modules
import { KintoneRestAPIClient } from '@kintone/rest-api-client'

使用

安裝好引入後,可以 new KintoneRestAPIClient 來使用:

const client = new KintoneRestAPIClient({
  baseUrl: "https://example.cybozu.com",
  // Use password authentication
  auth: {
    username: process.env.KINTONE_USERNAME,
    password: process.env.KINTONE_PASSWORD,
  },
  // Use API token authentication
  // auth: { apiToken: process.env.KINTONE_API_TOKEN }
  // Use OAuth token authentication
  // auth: { oAuthToken: process.env.KINTONE_OAUTH_TOKEN }

  // Use session authentication if `auth` is omitted (in browser only)
});

在分類上,套件把功能分成了五大類:

  • Record
  • App
  • Space
  • File
  • BulkRequest

然後再根據需求調用。比如我今天想要取得該應用程式的所有資料,就可以使用 getAllRecords

const response = await client.record.getAllRecords({app: '1', condition: 'price >= 1000'})

建立 Response 型別

以上面的 getAllRecords 為例,我們可以傳入自定義的 Record 型別,用這個函式提供的泛型,不過在此之前要先引用型別:

import type { KintoneRecordField } from '@kintone/rest-api-client'

之後建立型別並傳入:

type MyRecord = {
  field1: KintoneRecordField.SingleLineText
  field2: KintoneRecordField.Calc
}

client.record.getAllRecords<MyRecord>({app: '1', condition: 'price >= 1000'})

這是真的只發一次 API 嗎?

官網明明說只能拿到 500 筆,為什麼這個套件可以全部都拿到?即使是幾千筆。

其實套件只是發了很多次 request,最後再把結果集中起來 return 給我們而已,所以如果你拿了 1400 筆資料,kintone-rest-api-client 會幫我們發三次 API,所以對於請求次數很在意而使用這個套件的話,基本上是沒幫助,就只是它封裝成我們很好調用的方式而已。


這個套件是基於 axios 開發的,但卻不包含 axios 的某些功能,例如 interceptors 等,然後每次都要在函式中寫入應用程式 ID,個人覺得稍嫌麻煩了點。


上一篇
Day 10 | kintone × Typescript
下一篇
Day 12 | kintone 隱藏欄位內容,直到滑鼠經過
系列文
我阿嬤都會的 kintone 客製化開發13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言